#pragma once

#include <iostream>
#include <string>
#include <unistd.h>
#include "nocopy.hpp"
#include "InetAddr.hpp"
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include "Log.hpp"

static const int gsockfd = -1;
static const uint16_t gloaclport = 8888;

using namespace log_ns;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

// UdpServer user("192.1.1.1",8899);
class UdpServer : public nocopy
{
public:
    UdpServer( uint16_t loaclport = gloaclport)
        : _sockfd(gsockfd),
          _localport(loaclport),
          _isrunning(false)
    {
    }
    void InitServer()
    {
        // 1.创建socket文件
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "socket create success, _sockfd:%d\n", _sockfd); // 3
        // 2.bind
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport); // server的端口号，主机序列转为网络序列
        // local.sin_addr.s_addr = inet_addr(_localip.c_str()); // 1.需要4字节IP  2.需要网络序列的IP
        local.sin_addr.s_addr = INADDR_ANY; //服务器端，进行任意IP地址绑定

        int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "bind success\n");
    }
    void Start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&peer, &len);
            if (n > 0)
            {
                InetAddr addr(peer);
                // uint16_t client_port = ntohs(peer.sin_port);
                // std::string client_ip = inet_ntoa(peer.sin_addr);
                inbuffer[n] = 0;
                std::cout << "[" << addr.Ip() << ":" << addr.Port() << "]#" << inbuffer << std::endl;
                std::string echo_string = "[upd_server echo]#";
                echo_string += inbuffer;

                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (sockaddr *)&peer, len);
            }
        }
    }
    ~UdpServer()
    {
        if(_sockfd > gsockfd) ::close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _localport;
    // std::string _localip; // 后面要专门处理这个IP
    bool _isrunning;
};
